package com.study.shengsiyuan.example03;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {
	//存放所有连接的客户端channel
	private static  ChannelGroup  channelGroup
		= new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		Channel channel= ctx.channel();
		channelGroup.forEach(ch->{
			if(ch!=channel) {
				ch.writeAndFlush(channel.remoteAddress()+"发送的消息 : "+ msg +"\n");
			}else {
				ch.writeAndFlush("自己发送的消息 : "+ msg +"\n");
			}
		});
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Channel channel= ctx.channel();
		System.out.println(channel.remoteAddress()+"已经上线\n");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Channel channel= ctx.channel();
		System.out.println(channel.remoteAddress()+"已经下线\n");
	}


	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel channel= ctx.channel();
		channelGroup.writeAndFlush("【服务器】- "+ channel.remoteAddress() + "加入 \n");
		channelGroup.add(channel);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Channel channel= ctx.channel();
//		channelGroup.remove(channel); //netty 会自动调用
		channelGroup.writeAndFlush("【服务器】- "+ channel.remoteAddress() + "离线 \n");
		System.out.println(" --- 还有 "+channelGroup.size()+" 客户端程序在线 \n");
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelRegistered(ctx);
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelUnregistered(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}
